import styles from '../styles.less';
import { Modal, Pagination, Space, Table, Tag, Popover } from 'antd';
import { useCallback, useEffect } from 'react';
import Opera from './Opera';
import { connect, useAccess } from 'umi';
import { ExclamationCircleFilled } from '@ant-design/icons';
import { nowrapColumns } from '@/utils/utils';

const DataTable = (props) => {

  const { dispatch, dataTable, submitting, loading } = props;
  const { setSpecs, setCates, setDataForm, tablePayload, setTablePayload } = props.data;
  const access = useAccess();

  /* 获取列表 */
  const fetchList = useCallback((payload) => {
    dispatch({
      type: 'PMallGoods/fetchList',
      payload: payload,
    });
  }, [dispatch]);

  /* 查询监听 */
  useEffect(() => {
    fetchList(tablePayload);
  }, [fetchList, tablePayload]);

  /* 规格 */
  function specs(e, record) {
    e.preventDefault();
    setSpecs({
      visible: true,
      title: '规格管理',
      data: record,
    });
    return false;
  }

  /* 编辑 */
  function edit(e, record) {
    e.preventDefault();
    setDataForm({
      visible: true,
      title: '编辑操作',
      data: record,
    });
    return false;
  }

  /* 删除 */
  function del(e, record) {
    e.preventDefault();
    if (!submitting) {
      Modal.confirm({
        title: '提示',
        icon: <ExclamationCircleFilled />,
        content: '是否确定删除数据？',
        onOk() {
          dispatch({
            type: 'PMallGoods/del',
            payload: [record.id],
            callback: () => {
              setTablePayload({ ...tablePayload, pageNum: 1 });
            },
          });
        },
      });
    }
    return false;
  }

  /* 更新状态 */
  function status(e, record) {
    e.preventDefault();
    if (!submitting) {
      Modal.confirm({
        title: '提示',
        icon: <ExclamationCircleFilled />,
        content: record.status === 1 ? '是否确定下架？' : '是否确定上架',
        onOk() {
          dispatch({
            type: 'PMallGoods/status',
            payload: record.id,
            callback: () => {
              setTablePayload({ ...tablePayload, pageNum: 1 });
            },
          });
        },
      });
    }
    return false;
  }

  /* 更新状态 */
  function sellStatus(e, record) {
    e.preventDefault();
    if (!submitting) {
      Modal.confirm({
        title: '提示',
        icon: <ExclamationCircleFilled />,
        content: record.sellStatus === 1 ? '是否确定售罄？' : '是否确定售卖',
        onOk() {
          dispatch({
            type: 'PMallGoods/sellStatus',
            payload: record.id,
            callback: () => {
              setTablePayload({ ...tablePayload, pageNum: 1 });
            },
          });
        },
      });
    }
    return false;
  }

  const columns = [
    {
      title: '序号',
      width: 70,
      align: 'center',
      fixed: 'left',
      render: ({}, {}, index) => (
        <span>
          {(tablePayload.pageNum - 1) * tablePayload.pageSize + index + 1}
        </span>
      ),
    },
    {
      title: '商品名称',
      dataIndex: 'name',
      align: 'left',
      width: 300,
      ellipsis: true,
    },
    {
      title: '商品规格',
      dataIndex: 'mallGoodsSpecCount',
      align: 'center',
      render: (_, record) => {
        if (!access.mall_goodsSpec_list) {
          return (<span>-</span>);
        }
        return (
          <span style={{ color: '#1d39c4', cursor: 'pointer' }}
                onClick={e => specs(e, record)}>规格（{record.mallGoodsSpecCount}）</span>
        );
      },
    },
    {
      title: '当前售价',
      dataIndex: 'sellPrice',
      align: 'center',
      render: (_, record) => {
        return (
          <span style={{ color: '#d4380d' }}>￥ {(record.sellPrice / 100).toFixed(2)}</span>
        );
      },
    },
    {
      title: '有效期天',
      dataIndex: 'indate',
      align: 'center',
      render: (_, record) => {
        return (
          <span>{record.indate === 0 ? '永久有效' : `${record.indate} 天`}</span>
        );
      },
    },
    {
      title: '可用商家',
      dataIndex: 'mchCount',
      align: 'center',
      render: (_, record) => {
        if (record.mchCount <= 0) {
          return <span style={{ color: '#1d39c4' }}>{record.mchCount}</span>;
        }

        const content = (
          <div>
            {record.mallGoodsMchLinkList.map(d => {
              return (<div key={d}>{d.mchName}</div>);
            })}
          </div>
        );
        return (
          <Popover content={content}>
            <span style={{ color: '#1d39c4' }}>{record.mchCount}</span>
          </Popover>
        );
      },
    },
    {
      title: '售罄状态',
      dataIndex: 'sellStatus',
      align: 'center',
      render: (_, record) => {
        return (
          <Tag color={record.sellStatus === 1 ? 'geekblue' : 'volcano'}>
            {record.sellStatus === 1 ? '售卖' : '售罄'}
          </Tag>
        );
      },
    },
    {
      title: '当前状态',
      dataIndex: 'status',
      align: 'center',
      render: (_, record) => {
        return (
          <Tag color={record.status === 1 ? 'geekblue' : 'volcano'}>
            {record.status === 1 ? '已上架' : '已下架'}
          </Tag>
        );
      },
    },
    {
      title: '真实销量',
      dataIndex: 'sellNum',
      align: 'center',
      render: (_, record) => {
        return (
          <span>{record.sellNum}</span>
        );
      },
    },
    {
      title: '排序属性',
      dataIndex: 'orderby',
      align: 'center',
    },
    {
      title: '所属分类',
      dataIndex: 'cateName',
      align: 'center',
      render: (_, record) => {
        return (
          <span>{record.cateName ? record.cateName : '-'}</span>
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      align: 'center',
      width: 160,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          {access?.mall_goods_status && (
            <a onClick={e => status(e, record)}>{record.status === 1 ? '下架' : '上架'}</a>
          )}
          {access?.mall_goods_sellStatus && (
            <a onClick={e => sellStatus(e, record)}>{record.sellStatus === 1 ? '售罄' : '售卖'}</a>
          )}
          {access?.mall_goods_edit && (
            <a onClick={e => edit(e, record)}>编辑</a>
          )}
          {access?.mall_goods_del && (
            <a onClick={e => del(e, record)}>删除</a>
          )}
        </Space>
      ),
    },
  ];

  return (
    <>
      <div className={styles.myDataTable}>
        <Opera data={{ setCates, setDataForm }} />
        <Table
          className={styles.myTable} bordered={false} size={'middle'} columns={nowrapColumns(columns, dataTable.list)}
          dataSource={dataTable.list} rowKey={'id'}
          pagination={false} scroll={{ y: '100%' }} loading={loading}
        />
      </div>
      <Pagination
        pageSize={tablePayload.pageSize} current={tablePayload.pageNum} total={dataTable.total}
        className={styles.myPagination} size={'default'} hideOnSinglePage={false}
        showTotal={(total) => {
          return `共 ${total} 条记录`;
        }}
        pageSizeOptions={[15, 30, 60, 120]}
        showSizeChanger showQuickJumper={true}
        onChange={(page, pageSize) => {
          setTablePayload({ ...tablePayload, pageNum: page, pageSize: pageSize });
        }}
      />
    </>

  );
};

export default connect(({ loading, PMallGoods }) => {
  return {
    loading: loading.effects['PMallGoods/fetchList'],
    submitting: loading.effects['PMallGoods/del'] || loading.effects['PMallGoods/status'],
    dataTable: PMallGoods.dataTable,
  };
})(DataTable);
